package com.sskj.hangqing.ui.fragment;


import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.hangqing.R;
import com.sskj.hangqing.R2;
import com.sskj.hangqing.component.DaggerUserDataComponent;
import com.sskj.hangqing.presenter.CoinFragmentPresenter;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.RxBusCode;
import com.sskj.lib.base.BaseFragment;
import com.sskj.lib.bean.CoinBean;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.bean.enums.CoinEnum;
import com.sskj.lib.box.LiveDataBus;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CoinImgUtil;
import com.sskj.lib.util.CoinUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

@SuppressWarnings("ALL")
@Route(path = RConfig.HANG_FRAGMENT_COIN_LIST)
public class CoinListFragment extends BaseFragment<CoinFragmentPresenter> {
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.includeEmpty)
    FrameLayout includeEmpty;
    private SlimAdapter<CoinBean> slimAdapter;
    private Map<String, Disposable> timeMap = new HashMap<>();
    private HashMap<String, String> coinMap;
    @Inject
    UserViewModel userViewModel;
    @Autowired
    boolean isSlide = false;
    @Autowired
    String qu;
    @Autowired
    boolean isUpDown = false;
    @Autowired
    boolean isNew = false;
    @Autowired
    boolean isSelf = false;
    private UserData userData;


    @Override
    protected int getLayoutId() {
        return R.layout.hang_fragment_coin;
    }

    @Override
    public CoinFragmentPresenter getPresenter() {
        return new CoinFragmentPresenter();
    }

    @Override
    public void initView() {
        ARouter.getInstance().inject(this);
        DaggerUserDataComponent.create().inject(this);
        qu = "/USDT";
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(getActivity())
                .setPaintWidth((int) RudenessScreenHelper.pt2px(App.INSTANCE, 5))
                .setDividerColor(ContextCompat.getColor(App.INSTANCE, R.color.hangDivider))
        );

        slimAdapter = SlimAdapter.create().register(R.layout.hang_recy_item_coin, new SlimInjector<CoinBean>() {
            @Override
            public void onInject(CoinBean data, IViewInjector injector, List payloads) {
                if (payloads != null && !payloads.isEmpty()) {
                } else {
                    Glide.with(CoinListFragment.this)
                            .load(CoinImgUtil.img.get(data.getCode()))
//                            .apply(new RequestOptions().error(CoinEnum.getByCode(data.getCode()).getRes()))
                            .into((ImageView) injector.findViewById(R.id.ivCoin));
                }
                BigDecimal bigDecimal = new BigDecimal(data.getPrice()).setScale(CoinUtil.getPriceKeepNum(data.getCode()));
                injector
//                        .image(R.id.ivCoin, CoinImgUtil.img.get(data.getCode()))
                        .text(R.id.tvUSDT, data.getPrice())
                        .text(R.id.tvRMB, "≈ ¥ " + CoinUtil.keepRMB(data.getCnyPrice()))
                        .text(R.id.tvCode, data.getLCode())
                        .text(R.id.tvRate, data.getChangeRate())
                        .background(R.id.hang_main,data.isUp()?R.mipmap.hang_icon_coin_list_green:R.mipmap.hang_icon_coin_list_red)
//                        .background(R.id.tvRate, ContextCompat.getDrawable(App.INSTANCE, data.isUp() ? R.drawable.hang_shape_05c_corner30 : R.drawable.hang_shape_ff3_corner30))
                        .textColor(R.id.tvRate, data.isUp() ? getResources().getColor(R.color.hangGreen) : getResources().getColor(R.color.hangRed))
                ;

                ClickUtil.click(injector.findViewById(R.id.hang_main), () -> {
                    if (!isSlide) {
                        ARouter.getInstance().build(RConfig.HANG_MARKET)
                                .withString(Constans.CODE, data.getCode())
                                .withString(Constans.QU, qu)
                                .withBoolean(Constans.IS_BIBI, false)
                                .navigation();
                    }
                });
            }
        });
        slimAdapter.attachTo(recyclerView).updateData(new ArrayList());
    }

    public void updateUI(List<CoinBean> data) {
        if (includeEmpty == null || slimAdapter == null) {
            return;
        }
        if (data == null || data.size() == 0) {
            slimAdapter.updateData(new ArrayList<>());
            includeEmpty.setVisibility(View.VISIBLE);
            return;
        }
        includeEmpty.setVisibility(View.GONE);

        slimAdapter.updateData(data);

    }


    public void refreshCoin(CoinBean coinBean) {
        if (slimAdapter == null || slimAdapter.getData() == null || slimAdapter.getData().size() == 0) {
            return;
        }
        Flowable.fromIterable(slimAdapter.getData())
                .filter(item -> item.getCode().equals(coinBean.getCode()))
                .subscribe(item -> {
                    int position = slimAdapter.getData().indexOf(item);
                    slimAdapter.getData().set(position, coinBean);
                    slimAdapter.notifyItemChanged(position, 1);
                }, e -> {
                });
    }


    @Override
    public void initData() {
        mPresenter.getProduct(userData, qu, isUpDown, isNew, isSelf);
        LiveDataBus.get().with(RxBusCode.PUSH_COIN_BEAN_BIBI, CoinBean.class)
                .observe(this, this::refreshCoin);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isSelf) {
            mPresenter.getProduct(userData, qu, isUpDown, isNew, isSelf);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
